/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.googlecode.ivybeans.module;

import java.io.File;
import java.io.IOException;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Exceptions;

/**
 * Helper to manipulate file and path with independantly they are given relative
 * or absolute. 
 * @author lforet
 */
public class FileHelper {

    private static FileHelper instance;

    private FileHelper() {
    }

    public static FileHelper getInstance() {
        if (instance == null) {
            instance = new FileHelper();
        }
        return instance;
    }

    public String getPath(FileObject folder, File file) {
        try {
            if (file == null) {
                return null;
            }
            if (folder == null) {
                return (file.isFile()) ? file.getPath() : null;
            }
            FileObject fo = FileUtil.toFileObject(file);
            String toReturn = (FileUtil.isParentOf(folder, fo)) 
                    ? FileUtil.getRelativePath(folder, fo) 
                    : FileUtil.toFile(fo).getCanonicalPath();
            return toReturn;
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    public File getFile(FileObject folder, String path) {
        File toReturn = null;
        if (path == null || path.length() == 0) {
            toReturn = null;
        } else {
            toReturn = new File(path); // try with absolute path
            if (!toReturn.exists() && folder != null) {
                toReturn = new File(FileUtil.toFile(folder), path);
            }
        }
        return (toReturn != null && toReturn.isFile()) ? toReturn : null;
    }
}
